package com.example.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class CommonHttpService {

    private static final Logger log = LoggerFactory.getLogger(CommonHttpService.class);

    private final RestTemplate restTemplate;

    public CommonHttpService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 通用 HTTP 请求方法（返回完整响应）
     *
     * @param requestBody 请求体对象
     * @param url         请求的目标 URL
     * @return ResponseEntity 包含完整的响应信息
     */
    public ResponseEntity<String> forwardRequest(String requestBody, String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));

        HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            log.info("发送 HTTP 请求到 URL: {}，请求体: {}", url, requestBody);
            return restTemplate.postForEntity(url, requestEntity, String.class);
        } catch (Exception e) {
            String errorMessage = String.format("HTTP 请求过程中发生异常: %s", e.getMessage());
            log.error(errorMessage, e);
            throw e;
        }
    }

}


